package com.example.demo.controller;

import com.example.demo.common.BaseResponse;
import com.example.demo.common.MD5Util;
import com.example.demo.common.TokenUtils;
import com.example.demo.entity.Employee;
import com.example.demo.service.EmployeeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    TokenUtils tokenUtils;

    @Autowired
    private RedisTemplate redisTemplate;

    Logger logger = LoggerFactory.getLogger(EmployeeController.class);

    @PostMapping("/login")
    public BaseResponse login(@RequestBody Employee employee) throws NoSuchAlgorithmException {

        String username = employee.getEmpNo();
        String password = employee.getEmpPassword();
        logger.info("登录信息==>username:" + username + "\tpassword:" + password);
        logger.info(MD5Util.getMD5(password));
//        Employee loginEmp = employeeService.login(username, MD5Util.getMD5(password));
        Employee loginEmp = employeeService.login(username, password);
        //登录失败
        if (loginEmp == null) {
            return BaseResponse.fail().message("登录失败，用户名或密码错误");
        } else {
            String token = tokenUtils.getToken(loginEmp.getEmpId().toString(), password);
            logger.debug("当前用户token:" + token);
            //缓存token和部门id
            redisTemplate.opsForValue().set(token, loginEmp.getDeptId().toString(), 2, TimeUnit.HOURS);
            return BaseResponse.success().data("username", username).data("Authorization", token).data("userId", loginEmp.getDeptId());
        }

    }
}
